package com.zsw.proxy;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerHandler extends SimpleChannelInboundHandler<String>{
	
	private final Logger LOG = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public void channelRead0(ChannelHandlerContext ctx, String body) throws Exception {
		LOG.info("Client :{}", body);
        String[] pp = body.split("#");
        String method = pp[0];
        String params = null;
        if(pp.length > 1){
        	params = pp[1];
        }
        String[] cc = method.split(";");
        Object result = null;
        if(cc.length > 1){
        	Test test = TestImpl.class.newInstance();
        	Class<?>[] dd = new Class<?>[cc.length - 2];
        	for( int i = 2;i < cc.length; i++){
        		dd[i - 2] = Class.forName(cc[i]);
        	}
        	Method m = Test.class.getMethod(cc[1],dd);
        	result = m.invoke(test,(Object[])params.split(";"));
        }
        ctx.writeAndFlush(result);
   	}
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//    	ctx.writeAndFlush("你与服务器建立一个连接。");
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    	super.channelInactive(ctx);
    	LOG.info("客户端断开服务器");
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.disconnect();
        ctx.close();
    }
}
